import React, { Component } from 'react'
import PaginationTable from 'components/PaginationTable'
// import {BpmButtonSubmit,BpmButtonRecall} from 'yyuap-bpm';
import { actions } from 'mirrorx';
import { Button,Message,Modal, Loading } from 'tinper-bee';
import Select from 'bee-select';
import moment from "moment/moment";
import Header from 'components/Header';
import DelModal from 'components/DelModal';
import Viewer from 'react-viewer';
import 'react-viewer/dist/index.css';
import MonitorSampleForm from '../monitorSample-form';
import VerificationCargoModal from '../custom-modal/VerificationCargoModal.js';
import SampleAdded from '../custom-modal/SampleAdded.js';
import {deepClone} from 'utils';
import AcExport from '../monitorSample-export';
import ExportImgNew from '../custom-modal-new/ExportImgNew.js';
import './index.less'

export default class MonitorSamplePaginationTable extends Component {
    constructor(props){
        super(props);
        let self=this;
        this.state = {
            // 表格中所选中的数据，拿到后可以去进行增删改查
            
            step: 10,
            showModal:false,
            searchValues:{},
            visibleView:false,
            imgList:[],
            delData:[],
            selectData: [],
            column:[
                {
                    title: "磅单号",
                    dataIndex: "vbillcode",//planNo
                    key: "vbillcode",
                    width: 100
                },{
                    title: "抽样区",
                    dataIndex: "samplingArea",
                    key: "samplingArea",
                    width: 100
                },
                {
                    title: "抽样区照片",
                    dataIndex: "sampleAreaPhoto",
                    key: "sampleAreaPhoto",
                    width: 100,
                    render: function(text,record,index) {
                        if(!text) {
                            text = [];
                        }
                        return <img className="monitor-img" src={text[0]} onClick={() => {self.showView(text)}} />
                    }
                },
                {
                    title: "物料品种",
                    dataIndex: "materialVariety",
                    key: "materialVariety",
                    width: 200
                },
                {
                    title: "列数",
                    dataIndex: "columnNo",
                    key: "columnNo",
                    width: 100
                },
                {
                    title: "排数",
                    dataIndex: "rowNo",
                    key: "rowNo",
                    width: 100
                },
                {
                    title: "层数",
                    dataIndex: "layerNo",
                    key: "layerNo",
                    width: 100
                },
                {
                    title: "总包数",
                    dataIndex: "totalPackageNo",
                    key: "totalPackageNo",
                    width: 100
                },
                {
                    title: "抽样位置",
                    dataIndex: "samplingLocation",
                    key: "samplingLocation",
                    width: 100
                },{
                    title: "加抽位置",
                    dataIndex: "pumpingPosition",
                    key: "pumpingPosition",
                    width: 150,
                },{
                    title: "审核状态",
                    dataIndex: "auditStatus",
                    key: "auditStatus",
                    width: 100,
                    render: function(text) {
                        if(text == "N") {
                            return "未审核";
                        }else if(text == "Y") {
                            return "已审核";
                        }
                    }
                },{
                    title: "是否人工检测",
                    dataIndex: "humanVerifyFlag",
                    key: "humanVerifyFlag",
                    width: 100,
                    render: function(text) {
                        if(text == "true") {
                            return "是";
                        }else {
                            return "否";
                        }
                    }
                },{
                    title: "采购组织",
                    dataIndex: "purchasOrg",
                    key: "purchasOrg",
                    width: 100
                },
                
                {
                    title: "是否已加抽",
                    dataIndex: "isAddPumping",
                    key: "isAddPumping",
                    width: 100,
                    render: function(text) {
                        if(text == "2") {
                            return "未加抽";
                        }else if(text == "1") {
                            return "已加抽";
                        }else if(text == "~") {
                            return "未操作";
                        }
                    }
                }
            ]
        }
        
    }
    
    componentDidMount(){
        actions.monitorSample.loadList(this.props.queryParam);//table数据
    }
    /**
     * 编辑,详情，增加
     */

    cellClick = async (record,btnFlag) => {
        await actions.monitorSample.updateState({
            rowData : record,
        });

        let id = "";
        if(record){
            id = record["id"];
        }
        actions.routing.push(
            {
                pathname: 'monitorSample-edit',
                search:`?search_id=${id}&btnFlag=${btnFlag}`
            }
        )
    }

    // 删除操作
    delItem = (record, index) => {
        this.setState({
            showModal:true,
            delData:[{ id: record.id,ts: record.ts }]
        });

    }

    // 表格勾选回调函数，返回选中数据
    onTableSelectedData = (data,index) => {
        this.setState({selectData:data})

    }
    vertificationSearchCall = () => {
        actions.monitorSample.loadList(this.props.queryParam);
        this.setState({selectData:[]})
    }
    sampleSearchCall = () => {
        actions.monitorSample.loadList(this.props.queryParam);
        this.setState({selectData:[]})
    }

    // 分页单页数据条数选择函数
    onPageSizeSelect = (index, value) => {
        let queryParam = deepClone(this.props.queryParam);
        let {pageIndex, pageSize} = queryParam.pageParams;
        pageSize = value;
        queryParam['pageParams'] = { pageIndex, pageSize };
        actions.monitorSample.loadList(queryParam);
    }

    // 分页组件点击页面数字索引执行函数
    onPageIndexSelect = (value, type) => {
        let queryParam = deepClone(this.props.queryParam);
        let { pageIndex, pageSize } = queryParam.pageParams;
        pageIndex = value - 1;

        //let { pageIndex, pageSize } = getPageParam(value, type, queryParam.pageParams);
        queryParam['pageParams'] = { pageIndex, pageSize };
        this.setState({ selectedIndex: 0 }); //默认选中第一行
        actions.monitorSample.loadList(queryParam);
    }

    // 模态框确认删除
    onModalDel = async (delFlag)=>{
        let {delData} = this.state;
        if(delFlag){
            await actions.monitorSample.delItem({
                param: delData
            });
        }
        this.setState({
            showModal:false,
            delData:[]
        })
    }
    // 模板下载
    onLoadTemplate = () => {
        window.open(`${GROBAL_HTTP_CTX}/jx_monitorSample/excelTemplateDownload`)
    }

    // 导入成功回调函数
    handlerUploadSuccess = (data)=>{
        // 导入成功后，列表加载数据
        Message.create({content: '导入数据成功', color: 'success'});
        actions.monitorSample.loadList();
    }

    showView = (data) => {
        this.setState({
            visibleView:true,
            imgList:data
        })
    }

    // 导入删除回调函数
    handlerUploadDelete = (file) => {

    }

    // 导出
    exportExcel = () =>{
        let {selectData} = this.state;
        //actions.monitorSample.exportExcel(this.queryParams);
        if(selectData.length > 0) {
            actions.monitorSample.exportExcel({
                dataList : selectData
            });
        }else {
            Message.create({ content: '请选择导出数据', color : 'danger'  });
        }
    }

    // 动态设置列表滚动条x坐标
    getCloumnsScroll = (columns) => {
        let sum = 0;
        columns.forEach((da) => {
            sum += da.width;
        })
        return (sum);
    }

    onConfirmCancelPumping = () => {
        let {selectData} = this.state;
        actions.monitorSample.confirmCancelPumping(selectData[0]);
        actions.monitorSample.loadList(this.props.queryParam);
        this.setState({selectData:[]});

    }

    onConfirmVerify = () => {
        let {selectData} = this.state;
        actions.monitorSample.confirmVerify(selectData[0]);
        actions.monitorSample.loadList(this.props.queryParam);
        this.setState({selectData:[]})
    }

    onHumanVerify = () => {
        let {selectData} = this.state;
        let param = {
            pk_poundbill:selectData[0].pk_poundbill
        }
        actions.monitorSample.humanVerify(param);
        actions.monitorSample.loadList(this.props.queryParam);
        this.setState({selectData:[]})
    }

    getFlag = () => {
        let {selectData} = this.state;
        if(selectData.length == 0) {
            return {vertifyFlag:true,otherFlag:true};
        }
        if(selectData.length>1)  
        {
            Message.create({ content: '只能选择一条数据', color : 'warning'  });
            return {vertifyFlag:true,otherFlag:true};
        }
        if(selectData[0].auditStatus == 'Y') {
            return {vertifyFlag:true,otherFlag:true};
        }
        if(selectData[0].auditStatus != 'Y' && selectData[0].isAddPumping == '~'){
            return {vertifyFlag:true,otherFlag:false};
        }
        if(selectData[0].auditStatus != 'Y' && selectData[0].isAddPumping != '~'){
            return {vertifyFlag:false,otherFlag:true};
        }


    }

    render(){
        const self=this;
        let { list, showLoading, pageIndex, pageSize, totalPages , total,queryParam } = this.props;
        let {showModal,selectData,imgList,visibleView} = this.state;
        let exportProps = { total, pageIndex, pageSize, selectData, list,queryParam};
        // 将boolean类型数据转化为string
        list.forEach(function(item){
            Object.keys(item).forEach(function(key){
                if(typeof item[key] === 'boolean'){
                    item[key] = String(item[key]);
                }
             })
         })

         let {vertifyFlag,otherFlag} = this.getFlag()
        return (
            <div className='monitorSample-root'>
                <MonitorSampleForm { ...this.props }/>
                <div className='table-header'>
                    <VerificationCargoModal disabledFlag={otherFlag} selectData={selectData} vertificationSearchCall={this.vertificationSearchCall} />
                    <SampleAdded disabledFlag={otherFlag} selectData={selectData} sampleSearchCall={this.sampleSearchCall} />
                    <DelModal selectData={selectData} modalTitle="不加抽样本"  modalContent="确认不加抽样本？确认后将无法进行加抽抽样。"  confirmFn={this.onConfirmCancelPumping} >
                        <Button disabled={otherFlag} colors="primary" style={{"marginLeft":15}} size='sm' >
                        不加抽样本
                        </Button>
                    </DelModal>
                    <DelModal selectData={selectData} modalTitle="人工检测"  modalContent="确认设置成人工检测？此操作只能操作一次！"  confirmFn={this.onHumanVerify} >
                        <Button disabled={!(selectData.length == 1)} colors="primary" style={{"marginLeft":15}} size='sm' >
                            人工检测 
                        </Button>
                    </DelModal>
                    <DelModal selectData={selectData} modalTitle="审核通过"  modalContent="确认审核通过？审核通过后车辆将离开抽样区。"  confirmFn={this.onConfirmVerify} >
                        <Button disabled={vertifyFlag} colors="primary" style={{"marginLeft":15}} size='sm' >
                            审核通过
                        </Button>
                    </DelModal>
                    <ExportImgNew />
                    
                </div>
                <PaginationTable
                        data={list}
                        rowClassName={(record,index,indent)=>{
                          if (record.auditStatus == 'Y') {
                              return 'selected';
                          } else {
                              return 'aa';
                          }
                        }}
                        scroll={{x:true,y:500}}
                        pageIndex={pageIndex}
                        pageSize={pageSize}
                        totalPages={totalPages}
                        total = {total}
                        columns={this.state.column}
                        checkMinSize={6}
                        onTableSelectedData={this.onTableSelectedData}
                        onPageSizeSelect={this.onPageSizeSelect}
                        onPageIndexSelect={this.onPageIndexSelect}
                />
                <Loading show={showLoading} loadingType="line" />
                <Modal
                        show={showModal}
                        onHide={this.close} >
                    <Modal.Header>
                        <Modal.Title>确认删除</Modal.Title>
                    </Modal.Header>

                    <Modal.Body>
                        是否删除选中内容
                    </Modal.Body>

                    <Modal.Footer>
                        <Button onClick={()=>this.onModalDel(false)} style={{ marginRight: 50 }}>关闭</Button>
                        <Button onClick={()=>this.onModalDel(true)} colors="primary">确认</Button>
                    </Modal.Footer>
                </Modal>
                <Viewer
                    visible={visibleView}
                    onClose={() => { this.setState({ visibleView: false }); } }
                    images={imgList.map((li) => {
                        return {
                            src: `${li}`
                        }
                    }) }
                />
            </div>

        )

    }
}